package cn.edu.sgu.www.mhxysy.redis.repository.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.entity.except.Account;
import cn.edu.sgu.www.mhxysy.mapper.except.AccountMapper;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.redis.repository.RedisRepository;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class AccountRepository implements RedisRepository {

    private final RedisUtils redisUtils;
    private final AccountMapper accountMapper;

    public AccountRepository(RedisUtils redisUtils, AccountMapper accountMapper) {
        this.redisUtils = redisUtils;
        this.accountMapper = accountMapper;
    }

    @Override
    public void put(String id, Object value) {
        String key = RedisKeyPrefixes.PREFIX_ACCOUNT + id;

        if (value == null) {
            redisUtils.set(key, null);
        } else {
            redisUtils.set(key, JSON.toJSONString(value));
        }

        redisUtils.expire(key, 7, TimeUnit.DAYS);
    }

    @Override
    public Account selectById(String id) {
        String key = RedisKeyPrefixes.PREFIX_ACCOUNT + id;

        if (redisUtils.hasKey(key)) {
            log.debug("命中缓存{}", key);

            String value = redisUtils.get(key);

            if (value != null) {
                return JSON.parseObject(value, Account.class);
            }

            return null;
        }

        Account account = accountMapper.selectById(id);

        put(id, account);

        return account;
    }

    @Override
    public void putList(Object value) {
        String key = RedisKeyPrefixes.PREFIX_ACCOUNTS;

        redisUtils.set(key, JSON.toJSONString(value));
    }

    @Override
    public List<Account> selectList() {
        String key = RedisKeyPrefixes.PREFIX_ACCOUNTS;

        if (redisUtils.hasKey(key)) {
            log.debug("命中缓存{}", key);

            String value = redisUtils.get(key);

            if (value != null) {
                return JSON.parseArray(value, Account.class);
            }

            return null;
        }

        List<Account> list = accountMapper.selectList(null);

        putList(list);

        return list;
    }

    @Override
    public void deleteList() {
        String key = RedisKeyPrefixes.PREFIX_ACCOUNTS;

        redisUtils.delete(key);
    }

    @Override
    public void deleteById(String primaryKey) {
        redisUtils.delete(RedisKeyPrefixes.PREFIX_ACCOUNT + primaryKey);
    }

}